package com.yuyou.fn.tradingservice.controller;

import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.util.VerifyCodeUtils;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.service.IAreaTeamService;
import com.yuyou.fn.tradingservice.entity.*;
import com.yuyou.fn.tradingservice.service.*;
import com.yuyou.fn.tradingservice.vo.ServiceMerchantVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created by hboxs004 on 2017/4/10.
 */
@Controller
@RequestMapping(value = "/trading")
public class TradingServiceController extends TradingServiceBaseController {

    @Resource
    private IServiceProductService productService;

    @Resource
    private IShippingAddressService addressService;

    @Resource
    private IServiceMerchantService merchantService;

    @Resource
    private IServiceCartItemService cartItemService;

    @Resource
    private IServiceCartService cartService;

    @Resource
    private IServiceOrderService orderService;

    @Resource
    private IServiceCategoryService categoryService;

    public String code;

    @Resource
    private IServiceCommentService commentService;

    @Resource
    private IAreaTeamService areaTeamService;

    @ApiOperation("前端商品/服务详情")
    @RequestMapping(value = "/goodsDetail")
    public String goodsDetail(ModelMap model, @RequestParam(value = "productId") Long productId, HttpServletRequest request) {
        ServiceProduct product = productService.findById(productId);
        List<ServiceComment> commentList = commentService.findByProductId(productId);
        model.addAttribute("commentList", commentList);
        model.addAttribute("amount", commentList.size());
        model.addAttribute("productVo", product);
        if (product.getType() == 0) {
            return "product/product-detail";
        } else if (product.getType() == 1) {
            return "service/service-detail";
        } else {
            return "lease/lease-detail";
        }
    }

    @ApiOperation("前端商品/服务列表")
    @RequestMapping(value = "/goodsList")
    public String goodsList(ModelMap model, HttpServletRequest request,
                            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "6") int pageSize,
                            @RequestParam(value = "categoryId") Long categoryId, @RequestParam(value = "busTeamId") Long busTeamId,
                            @RequestParam(value = "productName") String productName) {
        Page<ServiceProduct> page = productService.findProductForPage(pageNo, pageSize, categoryId, busTeamId, productName);
        List<ServiceProduct> productList = page.getRecords();
        model.addAttribute("productList", productList);
        return "success";
    }

    @ApiOperation("获取验证码图片")
    @RequestMapping(value = "verifyCodeImage", method = {RequestMethod.GET, RequestMethod.POST})
    public void verifyCodeImage(HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        code = null;
        code = VerifyCodeUtils.generateVerifyCode(4);
        try {
            VerifyCodeUtils.outputImage(100, 50, response.getOutputStream(), code);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("服务商家注册")
    @RequestMapping(value = "/saveOrUpdateRegister")
    @ResponseBody
    public String saveOrUpdateRegister(ServiceMerchantVo serviceMerchantvo, HttpServletRequest request, HttpSession session) {
        SysUser sysUser = (SysUser) session.getAttribute("user");
        if (sysUser != null) {
            serviceMerchantvo.setUserId(sysUser.getUserId());
            serviceMerchantvo.setBusTeamId(sysUser.getBusTeamId());
        }
        if (!code.equals(serviceMerchantvo.getCode())) {
            return "fail";
        }
        Long merchantId = merchantService.saveOrUpdate(serviceMerchantvo);
        return merchantId.toString();
    }

    @ApiOperation("设置商家服务范围页面")
    @RequestMapping(value = "setMerchantService", method = {RequestMethod.POST, RequestMethod.GET})
    public String setMerchantService(@RequestParam("merchantId") String merchantId, ModelMap model) {
        Long id = Long.parseLong(merchantId);
        ServiceMerchant merchant = merchantService.findById(id);
        List<AreaTeam> areaTeams = areaTeamService.findListByExample(AreaTeam.createExample());
        List<ServiceCategory> categorys = categoryService.findListByExample(ServiceCategory.createExample());
        model.addAttribute("merchant", merchant);
        model.addAttribute("areaTeams", areaTeams);
        model.addAttribute("categorys", categorys);
        return "set-merchant-service";
    }

    @ApiOperation("前端租赁加入购物车")
    @RequestMapping(value = "/addRentToCart", method = {RequestMethod.GET, RequestMethod.POST})
    public String addRentToCart(HttpServletRequest request, @RequestParam(value = "startDate") String startDate,
                                @RequestParam(value = "endDate") String endDate, @RequestParam(value = "startTime") String startTime,
                                @RequestParam(value = "endTime") String endTime, @RequestParam(value = "productId") Long productId) {
        SysUser user = getUser(request);
        if (user == null) {
            return "login";
        }
        ServiceProduct product = productService.findById(productId);
        cartService.addRentToCart(product, user.getUserId(), startDate, endDate, startTime, endTime);
        return "success";
    }


    @ApiOperation("删除前端商品/租赁购物车里的所有商品")
    @RequestMapping(value = "/delFromCart", method = {RequestMethod.GET, RequestMethod.POST})
    public String delFromCart(@RequestParam(value = "cartItemIds[]") List<Long> cartItemIds, @RequestParam(value = "type") Integer type) {
        if (cartItemIds.size() > 0) {
            cartItemService.deleteBatchIds(cartItemIds);
            cartItemService.delServiceCartOrNot(type);
        }
        return "success";
    }

    @ApiOperation("删除前端商品/租赁购物车中的单个商品")
    @RequestMapping(value = "delServiceProductById", method = {RequestMethod.GET, RequestMethod.POST})
    public String  delServiceProductById(ModelMap model, @RequestParam(value = "cartItemId") Long cartItemId,@RequestParam(value="type") Integer type, HttpServletRequest request) {
        cartItemService.deleteById(cartItemId);
        List<ServiceCartItem> cartItemList = cartItemService.getAllCartItems(type);
        model.addAttribute("cartItemList", cartItemList);
        return "product/product-cart";
    }

    @ApiOperation("前端商品/租赁购物车列表")
    @RequestMapping(value = "/getGoodsCartItemList", method = {RequestMethod.GET, RequestMethod.POST})
    public String goodsCartItemList(ModelMap model, HttpServletRequest request, @RequestParam(value = "type") Integer type) {
        List<ServiceCartItem> cartItemList = cartItemService.getAllCartItems(type);
        model.addAttribute("cartItemList", cartItemList);
        return "success";
    }

    @ApiOperation("前端商品/租赁确认订单")
    @RequestMapping(value = "/orderInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public String orderInfo(@RequestParam(value = "cartItemIds") List<Long> cartItemIds, ModelMap model, HttpServletRequest request) {
        SysUser user = getUser(request);
        List<ShippingAddress> addressList = addressService.findAddressListByUserId(user.getUserId());
        List<ServiceCartItem> cartItemList = cartItemService.findByIds(cartItemIds);
        model.addAttribute("addressList", addressList);
        model.addAttribute("cartItemList", cartItemList);
        model.addAttribute("cartItemIds", cartItemIds);
        return "success";
    }

    @ApiOperation("前端商品/租赁提交订单")
    @RequestMapping(value = "/submitProductOrder", method = {RequestMethod.GET, RequestMethod.POST})
    public String submitProductOrder(ModelMap model, @RequestParam(value = "addressId", defaultValue = "0") Long addressId,
                                     HttpServletRequest request, @RequestParam(value = "cartItemIds") List<Long> cartItemIds) {
        //获取当前登录用户
        SysUser user = getUser(request);
        ServiceOrder order = orderService.generateOrder(addressId, user, cartItemIds);
        model.addAttribute("order", order);
        return "success";
    }

    @ApiOperation("前端服务提交订单")
    @RequestMapping(value = "submitServiceOrder", method = {RequestMethod.POST, RequestMethod.GET})
    public String submitServiceOrder(ModelMap model, @RequestParam(value = "phoneNo") String phoneNo, @RequestParam(value = "requirement") String requirement,
                                     @RequestParam(value = "productId") Long productId, @RequestParam(value = "quantity") int quantity,
                                     @RequestParam(value = "price") Long price, HttpServletRequest request) {
        SysUser user = getUser(request);
        ServiceProduct product = productService.findById(productId);
        ServiceOrder order = orderService.generateServiceOrder(user, product, requirement, phoneNo, quantity, price);
        model.addAttribute("order", order);
        return "service/service-order";
    }

    @ApiOperation("前端商品/服务/租赁支付后更新订单状态")
    @RequestMapping(value = "/payOrder", method = {RequestMethod.GET, RequestMethod.POST})
    public String payOrder(@RequestParam(value = "orderId") Long orderId, @RequestParam(value = "payWay") Integer payWay, HttpServletRequest request) {
        orderService.payOrder(orderId, payWay);
        return "success";
    }

    @ApiOperation("确认支付订单")
    @RequestMapping(value = "confirmPayOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String confirmPayOrder(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        orderService.confirmPayOrder(orderId);
        return "success";
    }

    @ApiOperation("取消的订单")
    @RequestMapping(value = "cancelOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String cancelOrder(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        orderService.cancelOrder(orderId);
        return "success";
    }

    @ApiOperation("退款的订单")
    @RequestMapping(value = "refundOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refundOrder(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        orderService.refundOrder(orderId);
        return "success";
    }

    @ApiOperation("确认收货")
    @RequestMapping(value = "confirmOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String confirmOrder(@RequestParam("orderId") Long orderId, HttpServletRequest request) {
        orderService.confirmOrder(orderId);
        return "success";
    }

    @ApiOperation("点击结算获取用户收货地址")
    @RequestMapping(value = "/getAddresses", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String getAddresses(HttpServletRequest request, ModelMap model) {
        SysUser user = getUser(request);
        List<ShippingAddress> addressList = addressService.findAddressListByUserId(user.getUserId());
        model.addAttribute("addressList", addressList);
        return "success";
    }

    @ApiOperation("获取所有分类")
    @RequestMapping(value = "getAllCategory", method = {RequestMethod.GET, RequestMethod.POST})
    public String getAllCategory(ModelMap model) {
        List<ServiceCategory> productList = categoryService.findCategoryByType(0);
        List<ServiceCategory> serviceList = categoryService.findCategoryByType(1);
        List<ServiceCategory> rentList = categoryService.findCategoryByType(2);
        model.addAttribute("productList", productList);
        model.addAttribute("serviceList", serviceList);
        model.addAttribute("rentList", rentList);
        return "product";
    }

    @ApiOperation("根据categoryId获取商品")
    @RequestMapping(value = "/productList", method = {RequestMethod.GET, RequestMethod.POST})
    public String productList(ModelMap model, @RequestParam(value = "categoryId") Long categoryId) {
        List<ServiceProduct> productList = productService.productDetail(categoryId);
        model.addAttribute("productList", productList);
        ServiceCategory category = categoryService.findById(categoryId);
        if (category.getType() == 0) {
            return "product/product-list";
        } else if (category.getType() == 1) {
            return "service/service-list";
        } else {
            return "lease/lease-list";
        }

    }

    @ApiOperation("登陆接口")
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(@RequestParam(value = "username") String username, @RequestParam("password") String password, @RequestParam(value = "captchaCode", required = false) String captchaCode, @RequestParam(value = "u", required = false) String uid, HttpSession session) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "login";
        }
        SysUser user = sysUserService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "success";
        }
        return "fail";
    }

}
